import 'package:flutter/material.dart';
import '../models/community.dart';
import '../utils/theme_colors.dart';

class CommunityFilterSheet extends StatefulWidget {
  final PostType? selectedType;
  final String? selectedTopicId;
  final List<Topic> topics;
  final Function(PostType?) onTypeChanged;
  final Function(String?) onTopicChanged;
  final VoidCallback onReset;
  final VoidCallback onApply;

  const CommunityFilterSheet({
    Key? key,
    this.selectedType,
    this.selectedTopicId,
    required this.topics,
    required this.onTypeChanged,
    required this.onTopicChanged,
    required this.onReset,
    required this.onApply,
  }) : super(key: key);

  @override
  State<CommunityFilterSheet> createState() => _CommunityFilterSheetState();
}

class _CommunityFilterSheetState extends State<CommunityFilterSheet> {
  PostType? _selectedType;
  String? _selectedTopicId;

  @override
  void initState() {
    super.initState();
    _selectedType = widget.selectedType;
    _selectedTopicId = widget.selectedTopicId;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(
          top: Radius.circular(20),
        ),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          _buildHeader(),
          Flexible(
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _buildTypeFilter(),
                  const SizedBox(height: 24),
                  _buildTopicFilter(),
                  const SizedBox(height: 32),
                  _buildActionButtons(),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildHeader() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(
            color: Colors.grey[200]!,
            width: 1,
          ),
        ),
      ),
      child: Row(
        children: [
          const Text(
            '筛选条件',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const Spacer(),
          IconButton(
            onPressed: () => Navigator.of(context).pop(),
            icon: const Icon(Icons.close),
          ),
        ],
      ),
    );
  }

  Widget _buildTypeFilter() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '帖子类型',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 12),
        Wrap(
          spacing: 8,
          runSpacing: 8,
          children: [
            _buildTypeChip(
              label: '全部',
              isSelected: _selectedType == null,
              onTap: () {
                setState(() {
                  _selectedType = null;
                });
              },
            ),
            ...PostType.values.map((type) {
              return _buildTypeChip(
                label: _getTypeText(type),
                isSelected: _selectedType == type,
                onTap: () {
                  setState(() {
                    _selectedType = type;
                  });
                },
              );
            }).toList(),
          ],
        ),
      ],
    );
  }

  Widget _buildTopicFilter() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '话题分类',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 12),
        Container(
          constraints: const BoxConstraints(maxHeight: 200),
          child: SingleChildScrollView(
            child: Column(
              children: [
                _buildTopicItem(
                  topic: null,
                  label: '全部话题',
                  isSelected: _selectedTopicId == null,
                ),
                ...widget.topics.map((topic) {
                  return _buildTopicItem(
                    topic: topic,
                    label: topic.name,
                    isSelected: _selectedTopicId == topic.id,
                  );
                }).toList(),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildTypeChip({
    required String label,
    required bool isSelected,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(
          horizontal: 16,
          vertical: 8,
        ),
        decoration: BoxDecoration(
          color: isSelected ? ThemeColors.primary : Colors.grey[100],
          borderRadius: BorderRadius.circular(20),
          border: isSelected
              ? Border.all(color: ThemeColors.primary)
              : Border.all(color: Colors.grey[300]!),
        ),
        child: Text(
          label,
          style: TextStyle(
            color: isSelected ? Colors.white : Colors.grey[700],
            fontSize: 14,
            fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
          ),
        ),
      ),
    );
  }

  Widget _buildTopicItem({
    required Topic? topic,
    required String label,
    required bool isSelected,
  }) {
    return ListTile(
      contentPadding: EdgeInsets.zero,
      leading: topic != null
          ? Container(
              width: 12,
              height: 12,
              decoration: BoxDecoration(
                color: Color(int.parse('0xFF${topic.color.substring(1)}')),
                shape: BoxShape.circle,
              ),
            )
          : const Icon(
              Icons.all_inclusive,
              size: 16,
              color: Colors.grey,
            ),
      title: Text(
        label,
        style: TextStyle(
          fontSize: 14,
          fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
          color: isSelected ? ThemeColors.primary : Colors.grey[800],
        ),
      ),
      trailing: topic != null
          ? Text(
              '${topic.postCount}',
              style: TextStyle(
                color: Colors.grey[600],
                fontSize: 12,
              ),
            )
          : null,
      selected: isSelected,
      selectedTileColor: ThemeColors.primary.withOpacity(0.1),
      onTap: () {
        setState(() {
          _selectedTopicId = topic?.id;
        });
      },
    );
  }

  Widget _buildActionButtons() {
    return Row(
      children: [
        Expanded(
          child: OutlinedButton(
            onPressed: () {
              setState(() {
                _selectedType = null;
                _selectedTopicId = null;
              });
              widget.onReset();
            },
            style: OutlinedButton.styleFrom(
              padding: const EdgeInsets.symmetric(vertical: 12),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8),
              ),
              side: BorderSide(color: Colors.grey[300]!),
            ),
            child: const Text(
              '重置',
              style: TextStyle(
                color: Colors.grey,
                fontSize: 16,
              ),
            ),
          ),
        ),
        const SizedBox(width: 12),
        Expanded(
          child: ElevatedButton(
            onPressed: () {
              widget.onTypeChanged(_selectedType);
              widget.onTopicChanged(_selectedTopicId);
              widget.onApply();
              Navigator.of(context).pop();
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: ThemeColors.primary,
              padding: const EdgeInsets.symmetric(vertical: 12),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8),
              ),
            ),
            child: const Text(
              '应用',
              style: TextStyle(
                color: Colors.white,
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ),
      ],
    );
  }

  String _getTypeText(PostType type) {
    switch (type) {
      case PostType.discussion:
        return '讨论';
      case PostType.question:
        return '提问';
      case PostType.sharing:
        return '分享';
      case PostType.announcement:
        return '公告';
    }
  }
}

// 显示筛选底部弹窗的辅助函数
void showCommunityFilterSheet({
  required BuildContext context,
  PostType? selectedType,
  String? selectedTopicId,
  required List<Topic> topics,
  required Function(PostType?) onTypeChanged,
  required Function(String?) onTopicChanged,
  required VoidCallback onReset,
  required VoidCallback onApply,
}) {
  showModalBottomSheet(
    context: context,
    isScrollControlled: true,
    backgroundColor: Colors.transparent,
    builder: (context) => CommunityFilterSheet(
      selectedType: selectedType,
      selectedTopicId: selectedTopicId,
      topics: topics,
      onTypeChanged: onTypeChanged,
      onTopicChanged: onTopicChanged,
      onReset: onReset,
      onApply: onApply,
    ),
  );
}